package com.st.common.security;

import com.st.core.entity.LoginRequest;
import com.st.core.entity.constant.ErrorConstants;
import com.st.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

/**
 * @author shent
 */
@Component
@Slf4j
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private AuthService authService;

    @Qualifier("SwordUserDetailsService")
    @Autowired
    UserDetailsService swordUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setUsername(authentication.getPrincipal().toString());
        loginRequest.setPassword(authentication.getCredentials().toString());
        // todo 登录添加验证码
        if (!loginRequest.isValid()) {
            throw new CredentialsExpiredException(ErrorConstants.ERROR_LOGIN_PARAMS);
        }
        authService.login(loginRequest);
        SwordUserDetails swordUserDetails = (SwordUserDetails) this.swordUserDetailsService.loadUserByUsername(loginRequest.getUsername());

        return new UsernamePasswordAuthenticationToken(swordUserDetails, null, swordUserDetails.getAuthorities());
    }

    /**
     * 这里表示此provider支持验证什么类型的token
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
